<?php
/**
 * 用户中心SDK
 * 
 * @author ShuangYa
 * @package EUser
 * @category SDK
 * @copyright Copyright (c) 2015-2016 ShuangYa
 * @link http://lab.sylingd.com/go.php?name=euser&type=license
 */

if (!class_exists('EUser_Packet', FALSE)) {
	require('EUser_Packet.php');
}

class EUser_swoole {
	protected $client;
	protected $config;
	protected $timer = NULL;
	public function __construct($config) {
		$this->config = $config;
	}
	protected function connect() {
		$this->client = new swoole_client(SWOOLE_SOCK_TCP | SWOOLE_KEEP);
		$this->client->connect($this->config['server']['addr'], $this->config['server']['port'], 3.0);
		$this->client->set([
			'open_length_check' => 1,
			'package_length_type' => 'N',
			'package_length_offset' => 0,
			'package_body_offset' => 4,
			'package_max_length' => 1024 * 1024 * 2,
			'open_tcp_nodelay' => 1
		]);
		//发送心跳包以维持连接
		if (strpos(PHP_SAPI, 'cli') === 0 && $this->timer === NULL) {
			$this->timer = swoole_timer_tick(4990, function($timer, $client) {
				try {
					$client->send(pack('N', 9) . 'heartbeat');
				} catch (\Exception $e) {
					//发包失败，取消定时任务
					swoole_timer_clear($timer);
				}
			}, $this->client);
		}
	}
	public function get($router, $data, $sign) {
		$sendData = ['router' => $router, 'data' => $data, 'sign' => $sign];
		if (!is_object($this->client) || !$this->client->isConnected) {
			$this->connect();
		}
		try {
			$this->client->send(EUser_Packet::packEncode($sendData));
			$r = EUser_Packet::packDecode($this->client->recv());
		} catch (\Exception $e) {
		}
		//出错重试
		if (!isset($r)) {
			$this->connect();
			try {
				$this->client->send(EUser_Packet::packEncode($sendData));
				$r = EUser_Packet::packDecode($this->client->recv());
			} catch (\Exception $e) {
				return NULL;
			}
		}
		if ($r['code'] !== 0) {
			return NULL;
		} else {
			return $r['data'];
		}
	}
}